import axios from 'axios'
import store from '../store/index'
import router from '@/router/index'
const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net/',
  timeout: 6000
})
// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const tokens = store.state.tokens
    if (tokens.token) {
      config.headers.Authorization = `Bearer ${tokens.token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (err) {
    if (err.response && err.response.status === 401) {
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default instance
